import * as customersService from '../services/customers';

export default {
  namespace: 'customers',
  state: {
    items: [],
    total: 0,
    page: 1,
    profile: {},
    study: {},
  },
  reducers: {
    save(
      state,
      {
        payload: { items, total, page },
      }
    ) {
      return { ...state, items, total, page };
    },
    saveProfile(
      state,
      {
        payload: { profile },
      }
    ) {
      return { ...state, profile };
    },
    saveStudy(
      state,
      {
        payload: { study },
      }
    ) {
      return { ...state, study };
    },
    saveLevels(
      state,
      {
        payload: { levels },
      }
    ) {
      return { ...state, levels };
    },
  },
  effects: {
    *fetchList(
      {
        payload: { page = 1, ...rest },
      },
      { call, put }
    ) {
      const { data } = yield call(customersService.fetchList, { page, ...rest });
      const { items, total } = data;
      yield put({
        type: 'save',
        payload: {
          ...rest,
          items,
          total,
          page: parseInt(page, 10),
        },
      });
    },
    *fetch({ payload: id }, { call, put }) {
      const { data: profile } = yield call(customersService.fetch, id);
      yield put({
        type: 'saveProfile',
        payload: {
          profile,
        },
      });
    },
    *fetchStudy({ payload: id }, { call, put }) {
      const { data: study } = yield call(customersService.fetchStudy, id);
      yield put({
        type: 'saveStudy',
        payload: {
          study,
        },
      });
    },
    *fetchLevels(payload, { call, put }) {
      const { data } = yield call(customersService.fetchLevels);
      const { items: levels } = data;
      yield put({
        type: 'saveLevels',
        payload: {
          levels,
        },
      });
    },
    *changeLevel(
      {
        payload: { id, level },
      },
      { call, put, select }
    ) {
      const response = yield call(customersService.changeLevel, id, level);
      const page = yield select(state => state.customers.page);
      yield put({ type: 'fetchList', payload: { page } });

      // 返回给dispatch回调then处理逻辑
      return response;
    },
    *update(
      {
        payload: { id, values },
      },
      { call, put, select }
    ) {
      yield call(customersService.update, id, values);
      const page = yield select(state => state.customers.page);
      yield put({ type: 'fetchList', payload: { page } });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/customers') {
          dispatch({ type: 'fetchList', payload: query });
        }
      });
    },
  },
};
